<?php

namespace app\common\business\user;

use app\common\mysql\Users as userSignMysql;
use app\common\business\user\Point as pointBn;
use app\common\business\User as userBn;

class UserSign extends \app\common\business\AbstractModel {

    /**
     * 签到明细
     * @param type params Description    
     * page
     * count
     * need_total
     * user_id
     */
    public static function signList($params) {

        self::_checkPageAndCount($params);
        $where = self::_getWhere($params);
        $listdata = userSignMysql::name('user_sign')
                ->where($where)
                ->limit($params['offset'], $params['count'])
                ->select();
        if (!empty($listdata)) {
            $listdata = self::_adapterList($listdata);
        }
        if (isset($params["need_total"]) && $params["need_total"] == 1) {
            return array("listdata" => $listdata, "total" => self::total($params));
        }
        return array("listdata" => (array) $listdata);
    }

    /**
     * 适配输出
     * 
     * @params  
     * @return array
     */
    protected static function _adapterList($result) {

        return $result;
    }

    /**
     * 获取where条件
     * 
     * @param array $params
     * @return array
     */
    protected static function _getWhere($params) {
        $where = array();
        if (isset($params["user_id"]) && !empty($params["user_id"])) {
            $where['user_id'] = $params["user_id"];
        }
        if (isset($params["start_time"]) && !empty($params["start_time"])) {
            $where['reg_time>='] = $params["start_time"];
        }
        if (isset($params["end_time"]) && !empty($params["end_time"])) {
            $where['reg_time<='] = $params["end_time"];
        }
        return $where;
    }

    /**
     * 计算总数
     * 
     * @param array $params
     * @return int
     */
    public static function total($params) {
        $where = self::_getWhere($params);
        $count = userSignMysql::name('user_sign')
                ->where($where)
                ->count();
        return $count;
    }

    /**
     *  是否签到
     * $user_id
     */
    public static function isSign($user_id) {
        $total = userSignMysql::name('user_sign')->where(array(
                    'user_id' => $user_id,
                ))
                ->whereTime('reg_time', 'today')
                ->count();
        return $total;
    }

    /**
     * 连续签到
     * 
     */
    public static function continuesignshow($user_id) {
        $cleartime = userSignMysql::name('user_money_log')->where(array('user_id' => $user_id, 'money_type' => 27, 'money' => 55))->order('log_id desc')->find();

        if (isset($cleartime['add_time']) && $cleartime['add_time'] >= strtotime('-7 days') && date("Y-m-d", $cleartime['add_time']) != date("Y-m-d")) {
            $start_time = strtotime(date("Y-m-d", $cleartime['add_time']) . ' 1 days');
        } else {
            $start_time = strtotime('-7 days');
        }
     
        $end_time = strtotime(date("Y-m-d 23:59:59").' -1 days');
          
        $daydata = userSignMysql::name('user_sign')->where(array(
                    'user_id' => $user_id,
                ))
                ->whereTime('reg_time', 'between', [$start_time, $end_time])
                ->order('reg_time DESC')
                ->select();
        $day_list = array(); 
        foreach ($daydata as $k => $v) {
            $day_list[] = date("Y-m-d", $v['reg_time']);
        }
        
        $data['daylist'] = array(0 => 5, 1 => 5, 2 => 8, 3 => 12, 4 => 18, 5 => 28, 6 => 40, 7 => 55);
        $data['continue_day'] = 0;
        $data['is_sign'] = self::isSign($user_id);
        $data['continue_day'] = 0; 
        if (count($day_list) >= 7) {
            $data['continue_day'] = 7;
            return $data;
        }
        if (count($day_list) >= 1) {
            for ($i = 1; $i <= count($day_list); $i++) {
                if (( abs(( strtotime(date('Y-m-d')) - strtotime($day_list[$i - 1]) ) / (3600 * 24))) == $i) {
                    $data['continue_day'] = $i;
                } else {
                    break;
                }
            }
        }

        return $data;    //输出连续几天
    }

    /**
     * 连续签到
     * 
     */
    public static function continuesign($user_id) { 
        
        $cleartime = userSignMysql::name('user_money_log')->where(array('user_id' => $user_id, 'money_type' => 27, 'money' => 55))->order('log_id desc')->find();
        if (isset($cleartime['add_time']) && $cleartime['add_time'] >= strtotime('-7 days') && date("Y-m-d", $cleartime['add_time']) != date("Y-m-d")) {
            $start_time = strtotime(date("Y-m-d", $cleartime['add_time']) . ' 1 days');
        } else {
            $start_time = strtotime('-7 days');
        }
        $end_time = strtotime(date("Y-m-d 23:59:59").' -1 days');
        $daydata = userSignMysql::name('user_sign')->where(array(
                    'user_id' => $user_id,
                ))
                ->whereTime('reg_time', 'between', [$start_time, $end_time])
                ->order('reg_time DESC')
                ->select();
        $day_list = array();

        foreach ($daydata as $k => $v) {
            $day_list[] = date("Y-m-d", $v['reg_time']);
        }
        $data['daylist'] = array(0 => 5, 1 => 5, 2 => 8, 3 => 12, 4 => 18, 5 => 28, 6 => 40, 7 => 55);
        $data['continue_day'] = 0;
        $data['is_sign'] = self::isSign($user_id);
        $data['continue_day'] = 0;
        if (count($day_list) > 7) {
            $data['continue_day'] = 0;
            return $data;
        }
        if (count($day_list) >= 1) {
            for ($i = 1; $i <= count($day_list); $i++) {
                if (( abs(( strtotime(date('Y-m-d')) - strtotime($day_list[$i - 1]) ) / (3600 * 24))) == $i) {
                    $data['continue_day'] = $i;
                } else {
                    break;
                }
            }
        }
        $data['continue_day'] = $data['continue_day'] + 1;
        return $data;    //输出连续几天
    }

    /**
     *  签到
     * @param type $params Description
     *  
     * $user_id
     */
    public static function addSign($parmas) {
        $total = userSignMysql::name('user_sign')->where(array(
                    'user_id' => $parmas['user_id'],
                ))
                ->whereTime('reg_time', 'today')
                ->count();
        if ($total > 0) {
            exception('已签到', 110037);
        }

        try {
            userSignMysql::startTrans();
            $parmas['source_type'] = 1;
             $datasign = self::continuesign($parmas['user_id']);
              if ($datasign['continue_day'] >= 0) {
               $parmas['point'] = $datasign['daylist'][$datasign['continue_day']];
               $parmas['money'] = $datasign['daylist'][$datasign['continue_day']];
              } 
            //日常操作积分
            $pointdata = pointBn::pointOperation($parmas);
            //记录签到
            $set['reg_time'] = time();
            $set['user_id'] = $parmas['user_id'];

            $r = userSignMysql::name('user_sign')->insert($set);
            if ($r != true) {
                userSignMysql::rollback();
                exception('签到失败', 110038);
            }
            //签到记录赠送积分 

            if ($pointdata['point'] > 0) {

                $change['change_memo'] = '签到获得'.$pointdata['point'].'积分';
                $change['user_id'] = $parmas['user_id'];
                $change['change_point'] = $pointdata['point'];
                $change['change_type'] = 1;
                $change['source_type'] = 1;

                $r =  pointBn::updatePoint($change);
                if ($r != true) {
                    userSignMysql::rollback();
                    exception('签到失败', 110038);
                }
            }
             //签到送金豆
            $updatemoney['user_id'] = $parmas['user_id'];
            $updatemoney['money_type'] = 27;
            $updatemoney['money'] = $parmas['money'];
            $updatemoney['memo'] = "签到获得";
            $r2 = userBn::updateMoney($updatemoney); 
            if ($r2 != true) {
                userSignMysql::rollback();
                exception('签到失败', 110038);
            }

            userSignMysql::commit();
           // $data['total_point'] = pointBn::mypoint($parmas['user_id']);
            $data['point'] = $pointdata['point'];
            $data['title'] = '已签到';
            $data['is_sign'] = 1;
        } catch (\Exception $e) {
            userSignMysql::rollback();
            exception($e->getMessage(), $e->getCode());
        }
        return $data;
    }

}
